package com.pg.controller;

import com.pg.dto.LoginDto;
import com.pg.entity.BackendUser;
import com.pg.entity.DevUser;
import com.pg.service.BackendUserService;
import com.pg.service.DevUserService;
import com.pg.sys.SystemUtils;
import com.pg.utils.SessionUtils;
import com.pg.vo.LoginVo;
import com.pg.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@RestController
@RequestMapping()
public class LoginController {

    @Autowired
    DevUserService devUserservice;

    @Autowired
    BackendUserService backendUserService;

    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginDto loginDto){

        if (loginDto.getUserType() == 1) {
            //admin未测试
            BackendUser backendUser= backendUserService.login(loginDto);

            StringBuffer random=new StringBuffer( UUID.randomUUID().toString().replace("-",""));
            random.append("-"+System.currentTimeMillis()+"-"+SystemUtils.user.admin+"-"+backendUser.getUsercode());
            String token=random.toString();


            LoginVo loginVo = new LoginVo();
            loginVo.setCode(backendUser.getUsercode());
            loginVo.setId(backendUser.getId());
            loginVo.setUserName(backendUser.getUsername());
            loginVo.setUserType(1);
            loginVo.setToken(token);

            SessionUtils.put(token,loginVo);

            return ResultVo.success("管理员登陆成功",loginVo);
        } else if (loginDto.getUserType() == 2) {
            DevUser devUser=devUserservice.login(loginDto);
            if (devUser==null){
                return ResultVo.error("账号或密码输入错误");
            }
            StringBuffer random=new StringBuffer( UUID.randomUUID().toString().replace("-",""));
            random.append("-"+System.currentTimeMillis()+"-"+SystemUtils.user.dev+"-"+devUser.getDevcode());
            String token=random.toString();


            LoginVo loginVo = new LoginVo();
            loginVo.setCode(devUser.getDevcode());
            loginVo.setId(devUser.getId());
            loginVo.setUserName(devUser.getDevname());
            loginVo.setUserType(2);
            loginVo.setToken(token);

            SessionUtils.put(token,loginVo);


            return ResultVo.success("开发者登陆成功",loginVo);
        } else {
            return ResultVo.error("登录类型异常，没有此合法角色");
        }
    }

    @GetMapping("/logout")
    public ResultVo logout(HttpServletRequest request){
       try {
           String token = request.getHeader("z");
           SessionUtils.remove(token);
           return ResultVo.success("注销成功", null);
       }catch (Exception e){
           e.printStackTrace();
           return ResultVo.error(e.getMessage() );
       }
    }
}
